package com.sylli.oeuf.server.db.sql;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import com.sylli.oeuf.server.db.DatabaseCache;
import com.sylli.oeuf.server.object.transferable.BasedTO;

public class MySQLGenericCache<T extends BasedTO> implements DatabaseCache<T> {

	private Map<Integer, WeakReference<T>> weakMap = new HashMap<Integer, WeakReference<T>>();
	
	public void addItemToCache(T obj) {
		weakMap.put(obj.hashCode(), new WeakReference<T>(obj));
	}

	public T getItemFromCache(long id) {
		if (weakMap.containsKey(id)) {
			T obj = weakMap.get(id).get();
			if (obj == null) {
				removeItemFromCache(id);
				return null;
			} else {
				return obj;
			}
		}
		return null;
	}

	public boolean isAlreadyInCache(long id) {
		if (weakMap.containsKey(id)) {
			T obj = weakMap.get(id).get();
			if (obj == null) {
				removeItemFromCache(id);
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	public void removeItemFromCache(long id) {
		weakMap.remove(id);
	}

}
